﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data.DBModels;
using Data.MyDbContext;
using System.Collections;

namespace DAL.Repositories
{
    public class WebsiteRepository : RepositoryPublic<Website>
    {
         public WebsiteRepository()
        {
            DB = new WebStudioDbContext();
        }

        public WebsiteRepository(DbContext db)
            : base(db)
        { }

        public WebsiteRepository(DbContextFactory db)
            : base(db)
        { }


        public bool UpdateWithCategories(Website websiteToUpdate, Guid[] categoryIds)
        {
            if (websiteToUpdate == null) throw new ArgumentNullException("websiteToUpdate cannot be null...");

            if (websiteToUpdate.Categories != null) {
                //List<Category> cates = new List<Category>();
                 var cates=  websiteToUpdate.Categories.ToList();
                foreach (Category cate in cates)
            {
                if(!categoryIds.Contains(cate.Id))
                {
                    websiteToUpdate.Categories.Remove(cate);
                }
            }
        }

            if (categoryIds != null)
            {
                foreach (Guid cid in categoryIds)
                {
                    if (!websiteToUpdate.Categories.Any(item => item.Id == cid))
                    {
                        Category c = DB.Set<Category>().Find(cid);
                        websiteToUpdate.Categories.Add(c);
                    }

                }
            }

            return Update(websiteToUpdate);
            

        }

        public bool CreateWithCategories(Website websiteToUpdate, Guid[] categoryIds)
        {
            if (websiteToUpdate == null) throw new ArgumentNullException("websiteToUpdate cannot be null...");

            websiteToUpdate.Categories = new List<Category>();

            if (categoryIds != null)
            {
                foreach (Guid cid in categoryIds)
                {
                        websiteToUpdate.Categories.Add(DB.Set<Category>().Find(cid));
                    
                }
            }

            return Add(websiteToUpdate);
        }
    }
}
